import numpy as np
import cv2
import requests, json
import tempfile
import os

from pydub import AudioSegment
from moviepy.editor import AudioFileClip, VideoFileClip, CompositeVideoClip

# pip install opencv-contrib-python
# pip install opencv-python
# pip install opencv-python-headless
# pip install pydub
# pip install moviepy
# yum install mesa-libGL


class myOpencv:
    """opencv图转视频"""

    def doWorking(self, *args, **kwargs):

        fd, video_name = tempfile.mkstemp(suffix=".mp4", text=True)
        # video_name = "/opt/output_video.mp4"
        try:
            image = self.downloadres(kwargs.get("image"))
            audio = self.downloadres(kwargs.get("audio"))
            length = self.hasLength(audio)
        except BaseException as err:
            raise Exception(f"[opencv] 加载文件 {err}")
        # 读取第一张图片，获取其尺寸信息
        frame = cv2.imread(image)
        height, width, layers = frame.shape
        # 使用VideoWriter对象创建视频
        # cv2.VideoWriter_fourcc(*"mp4v") #.m4v
        # cv2.VideoWriter_fourcc("X", "V", "I", "D") #.avi
        # cv2.VideoWriter_fourcc("X", "2", "6", "4"),  # .mp4
        try:
            video = cv2.VideoWriter(
                video_name,
                cv2.VideoWriter_fourcc(*"mp4v"),  # .m4v
                30,
                (width, height),
            )  # 修改帧率为2帧每秒， 其中数字2是调整视频的帧率的
            i = 0
            while i < length * 30:
                video.write(frame)
                i += 1
            # 释放VideoWriter对象
            video.release()
        except BaseException as err:
            raise Exception(f"[opencv] 创建视频失败 {err}")
        # return video_name
        # 合成
        try:
            output_file = self.merge_video(video_name, audio)
        except BaseException as err:
            raise Exception(f"[opencv] 合成视频失败 {err}")
        os.remove(image)
        os.remove(audio)
        os.remove(video_name)

        return output_file

    @staticmethod
    def merge_video(v, a):
        """合成视频"""
        fd, video_name = tempfile.mkstemp(suffix=".mp4", text=True)

        video = VideoFileClip(v)
        audio = AudioFileClip(a)

        video_duration = video.duration
        audio_duration = audio.duration

        if audio_duration > video_duration:
            audio = audio.subclip(0, video_duration)
        elif audio_duration < video_duration:
            video = video.subclip(0, audio_duration)

        final_clip = video.set_audio(audio)
        final_clip.write_videofile(video_name, codec="libx264", audio_codec="aac")
        # final_clip.write_videofile(video_name)
        return video_name

    @staticmethod
    def hasLength(audio):
        """计算长度"""
        # af = AudioSegment.from_wav(audio)
        # af = AudioSegment.from_mp3(audio)

        # af = AudioSegment.from_ogg(audio)
        # af = AudioSegment.from_flv(audio)

        # af = AudioSegment.from_file(audio, "mp4")
        # af = AudioSegment.from_file(audio, "wma")
        # af = AudioSegment.from_file(audio, "aac")

        af = AudioSegment.from_file(audio, audio.split(".")[-1])
        return af.duration_seconds

    @staticmethod
    def downloadres(url):
        """下载资源"""
        exp = url.split(".")
        fd, filepath = tempfile.mkstemp(suffix=f".{exp[-1]}", text=True)
        r = requests.get(url, stream=True)
        with open(fd, "wb") as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
        return filepath


# myOpencv = myOpencvDev()
